package com.mmall.service.impl;/**
 * Created by 果果 on 2017/8/2.
 */


import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author 果果
 * @描述 用户service实现类
 * @create 2017-08-02 22:19
 **/
@Service("iUserService")

public class UserServiceImpl  implements IUserService{


    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public ServerResponse<User> login(String username, String password) {
        int  count=userMapper.checkUsername(username);
        if (count==0){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        String  md5Password= MD5Util.MD5EncodeUtf8(password);//将密码进行Md5加密
        User user=userMapper.selectLogin(username,md5Password);
        if(user==null){
            return ServerResponse.createByErrorMessage("密码不正确");
        }
        //将用户信息中的密码置空
        user.setPassword(StringUtils.EMPTY);
        return  ServerResponse.createBySuccess("登录成功",user);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> register(User user){
        ServerResponse validResponse=this.checkValid(user.getUsername(),Const.USERNAME);
        if (!validResponse.isSuccess()){
            return  validResponse;
        }
        validResponse=this.checkValid(user.getEmail(),Const.EMAIL);
        if (!validResponse.isSuccess()){
            return  validResponse;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount=userMapper.insert(user);
        if(resultCount==0){
            return  ServerResponse.createByErrorMessage("注册失败");
        }
       return ServerResponse.createBySuccessMessage("注册成功");
    }

    /**
     * 验证用户名和邮箱收否已经使用过
     * @param str
     * @param type
     * @return
     */
    public ServerResponse<String> checkValid(String str,String type){
       if(StringUtils.isNotBlank(type)){
           if (Const.USERNAME.equals(type)){
               int count=userMapper.checkUsername(str);
               if (count>0){
                   return  ServerResponse.createByErrorMessage("用户名已存在");
               }
           }
           if (Const.EMAIL.equals(type)){
               int count=userMapper.checkEmail(str);
               if(count>0){
                   return ServerResponse.createByErrorMessage("邮箱已存在");
               }
           }
       }else{
           return ServerResponse.createByErrorMessage("参数错误");
       }
       return ServerResponse.createBySuccessMessage("校验成功");
    }

    /**
     * 根据用户名查询用户的问题
     * @param username
     * @return
     */
    @Override
    public ServerResponse<String> SelectQuestion(String username) {
        ServerResponse validResponse=this.checkValid(username,Const.USERNAME);
        if(!validResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String question=userMapper.selectQuestionByUsername(username);
        if(StringUtils.isNotBlank(question)){
           return  ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    /**
     * 验证用用户输入的问题和答案是否正确，并将token,放入缓存中
     * @param username
     * @param question
     * @param answer
     * @return
     */
    @Override
    public ServerResponse forgetCheckAnswer(String username, String question, String answer) {
        int  countResult=userMapper.checkAnswer(username,question,answer);
        //大于0,说明用户的答案是正确的，并且是这个用户的
        if (countResult>0){
          //生成token
            String  forgetToken= UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题答案错误");
    }

    /**
     * 忘记密码时的修改密码的提交----用户未登录状态
     * @param username
     * @param passwordNew
     * @param forgetToken
     * @return
     */
    @Override
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) {
        if (StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数有误，Token没有获取到");
        }
        ServerResponse validResponse=this.checkValid(username,Const.USERNAME);
        if (validResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        String  forToken=TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if (StringUtils.isBlank(forToken)){
            return ServerResponse.createByErrorMessage("token无效或者过期");
        }
        if (StringUtils.equals(forgetToken,forToken)){
            String md5Password=MD5Util.MD5EncodeUtf8(passwordNew);//将新密码加密
            int updateCount=userMapper.update_passwordBy_Username(md5Password,username);
            if (updateCount>0){
                return ServerResponse.createBySuccessMessage("密码修改成功");
            }

        }else {
            return ServerResponse.createByErrorMessage("token有误，请重新获取重置密码的token");
        }
       return ServerResponse.createByErrorMessage("修改密码失败");
    }


    /**
     * 修改密碼的提交----登陸時
     * @param passwordOld
     * @param passwordNew
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user) {
        int userCount=userMapper.checkUserPassword(MD5Util.MD5EncodeUtf8(passwordOld),user.getId());
        if (userCount==0){
            return  ServerResponse.createByErrorMessage("旧密码有误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount=userMapper.updateByPrimaryKeySelective(user);
        if (updateCount>0){
            return ServerResponse.createBySuccess("密码修改成功");
        }
       return  ServerResponse.createByErrorMessage("密码修改失败");
    }

    /**
     * 更新个人基本信息
     * @param user
     * @return
     */
    @Override
    public ServerResponse<User> updateUserInfo(User user) {
        int countResult=userMapper.checkUserEmailById(user.getEmail(),user.getId());
        if (countResult>0){
            return ServerResponse.createByErrorMessage("改邮箱已存在，请更换其他email尝试");
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setAnswer(user.getAnswer());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        int countUpdate=userMapper.updateByPrimaryKeySelective(updateUser);
        if (countUpdate>0){
            return  ServerResponse.createBySuccess("个人基本信息更新成功",updateUser);
        }
        return ServerResponse.createByErrorMessage("个人基本信息更新失败");
    }

    /**
     * 根据Id查询用户的基本信息
     * @param id
     * @return
     */
    @Override
    public ServerResponse<User> get_Information(Integer id) {
        User user=userMapper.selectByPrimaryKey(id);
        if (user==null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    /**
     * 检查是不是管理员
     * @param user
     * @return
     */
    @Override
    public ServerResponse checkAdminRole(User user) {
      if (user!=null&&user.getRole().intValue()==Const.Role.ROLE_ADMIN){
          return  ServerResponse.createBySuccess();
      }
        return ServerResponse.createByError();
    }
}
